package com.mybatis.plug.slicingStrategy;

import cn.hutool.core.util.StrUtil;
import com.mybatis.plug.TableSlicing;
import com.mybatis.plug.util.SqlStringUtil;

/**
 * Created by
 * update:判断表是否需要分表优化,不读注解,从分表manager处理
 *
 * @author dw
 * @date 2018/11/24
 */
public class SlicingUtil {
    public static String dealSqlByStrategy(String originalSql, StrategyManager strategyManager) {
        //单表分表:目前只是日志表,都是单表分表 如果考虑分表会联合查询,需要按下面逻辑兼容
        //TODO:多表关联下的表名提取记录 应该返回集合

        //分表处理后的sql
        String convertedSql = null;
        try {
            String tableName = SqlStringUtil.getTableName(originalSql);
            if (StrUtil.equalsIgnoreCase(tableName, "dual")) {
                return null;
            }

            if (!strategyManager.isSlicingTables(tableName)) {
                return null;//不是需要分表操作的表直接返回
            }
            Class<?> classObj = strategyManager.getSlicingTablesEntity(tableName);

            //logger.debug("分表前的SQL：{},entityClassStr {} tableName {} ", originalSql, entityClassStr, tableName);
            TableSlicing tableSplit = classObj.getAnnotation(TableSlicing.class);
            //读取entity分表注解
            if (tableSplit != null && tableSplit.slicing()) {
                String key = tableSplit.strategy();
                // 根据key获取切割策略
                Strategy strategy = strategyManager.getStrategy(key);
                convertedSql = originalSql.replaceAll(tableSplit.value(), strategy.returnTableName(tableSplit.value()));
                return convertedSql;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
